import { DataSource } from 'typeorm';
import { User } from '../../../entities/user.entity';
import { Role } from '../../../entities/role.entity';

/**
 * 用户-角色关联表种子数据
 * 负责初始化用户和角色的关联关系
 */
export class UserRoleSeed {
  constructor(private dataSource: DataSource) {}

  /**
   * 运行用户-角色关联种子
   */
  async run(): Promise<void> {
    console.log('开始初始化用户-角色关联数据...');

    const userRepository = this.dataSource.getRepository(User);
    const roleRepository = this.dataSource.getRepository(Role);

    // 查找基础用户
    const adminUser = await userRepository.findOne({
      where: { username: 'admin' },
      relations: ['roles']
    });

    const normalUser = await userRepository.findOne({
      where: { username: 'user' },
      relations: ['roles']
    });

    const guestUser = await userRepository.findOne({
      where: { username: 'guest' },
      relations: ['roles']
    });

    if (!adminUser || !normalUser || !guestUser) {
      console.log('未找到基础用户，跳过用户-角色关联初始化');
      return;
    }

    // 查找基础角色
    const adminRole = await roleRepository.findOneBy({ code: 'admin' });
    const userRole = await roleRepository.findOneBy({ code: 'user' });
    const guestRole = await roleRepository.findOneBy({ code: 'guest' });

    if (!adminRole || !userRole || !guestRole) {
      console.log('未找到基础角色，跳过用户-角色关联初始化');
      return;
    }

    // 为管理员用户分配管理员角色
    if (!adminUser.roles || !adminUser.roles.some(role => role.id === adminRole.id)) {
      adminUser.roles = adminUser.roles || [];
      adminUser.roles.push(adminRole);
      await userRepository.save(adminUser);
      console.log(`为用户 ${adminUser.username} 分配了角色 ${adminRole.name}`);
    }

    // 为普通用户分配普通角色
    if (!normalUser.roles || !normalUser.roles.some(role => role.id === userRole.id)) {
      normalUser.roles = normalUser.roles || [];
      normalUser.roles.push(userRole);
      await userRepository.save(normalUser);
      console.log(`为用户 ${normalUser.username} 分配了角色 ${userRole.name}`);
    }

    // 为访客用户分配访客角色
    if (!guestUser.roles || !guestUser.roles.some(role => role.id === guestRole.id)) {
      guestUser.roles = guestUser.roles || [];
      guestUser.roles.push(guestRole);
      await userRepository.save(guestUser);
      console.log(`为用户 ${guestUser.username} 分配了角色 ${guestRole.name}`);
    }

    console.log('用户-角色关联数据初始化完成');
  }
} 